package com.h3bpm.web.organization.service.impl;

import OThinker.Common.Organization.Models.OrganizationUnit;
import OThinker.Common.Organization.Models.Unit;
import OThinker.Common.Organization.Models.User;
import OThinker.Common.Organization.enums.State;
import OThinker.Common.Organization.enums.UserGender;
import OThinker.Common.Organization.enums.VisibleType;
import com.h3bpm.base.engine.client.EngineClient;
import com.h3bpm.base.util.AppUtility;
import com.h3bpm.web.common.utils.SqlUtil;
import com.h3bpm.web.organization.dao.DepartmentDao;
import com.h3bpm.web.organization.dao.UserDao;
import com.h3bpm.web.organization.service.OrganizationSyncService;
import data.DataRow;
import data.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @authormi
 * @date2019/12/6
 */
@Order(1)
@Service
public class OrganizationSyncServiceImpl implements OrganizationSyncService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrganizationSyncServiceImpl.class);

    @Autowired
    private DepartmentDao departmentDao ;

    @Autowired
    private UserDao userDao ;

    private static volatile EngineClient Engine = null;
    private static volatile boolean shouldRefreshEngine = false;

    public User getAdministrator() throws Exception {
        User user = getEngine().getOrganization().GetUserByCode("Administrator");
        return user;
    }

    public static EngineClient getEngine() {
        if (Engine == null || shouldRefreshEngine) {
            try {
                Engine = (EngineClient) AppUtility.getEngine();
            } catch (Exception e) {
                LOGGER.error("get engine fail", e);
                throw new RuntimeException(e);
            }
            shouldRefreshEngine = false;
        }
        return Engine;
    }

    @Override
    public String syncDepartmentService() {
        String result = "200";
        try {
            try {
                getEngine().getOrganization().Reload();
            } catch (Exception e) {
                e.printStackTrace();
            }
           String getH3UnSql= " select objectid,extend1 from ot_organizationunit  where extend1 = ";
           String getH3ParentUnSql= " select objectid,extend2 from ot_organizationunit  where extend2 = ";
            List<DataRow> masonDepartmentList = departmentDao.getDepartmentList();
            for(DataRow userData : masonDepartmentList) {
                DataTable isUnit = SqlUtil.doQuery(getH3UnSql+"'"+userData.getString("dept_code")+"'");
                if(!(isUnit.getEntityRows().size()>0) || isUnit==null) {
                    OrganizationUnit unit = new OrganizationUnit();
                    unit.setName(userData.getString("dept_content"));//名称
                    unit.setIsRootUnit(false);//是否是根节点
                    unit.setSortKey(0);//排序值
                    if(userData.getString("dept_deleted").equals("1")){
                        unit.setState(State.Inactive);
                    }else {
                        unit.setState(State.Active);
                    }
                    //Inactive(0),禁用 Active(1),启用 Unspecified(-1);
                    unit.setVisibility(VisibleType.Normal); //Normal(1),普通，同AllOnlyAdmin(2),管理员可见OnlyOrganization(4),仅本组织范围可见All(5);
                    unit.setParentIndex(0);
                    unit.setDescription(userData.getString("dept_id"));
                    unit.setExtend1(userData.getString("dept_code"));//组织iD
                    unit.setExtend2(userData.getString("dept_parentcode"));//所属组织 上级
                    getEngine().getOrganization().AddUnit(getAdministrator().getObjectID(), unit);//创建组织

                }else {
                    DataTable thisUnit = SqlUtil.doQuery(getH3UnSql + "'" + userData.getString("dept_code") + "'");
                    if (thisUnit != null && thisUnit.getEntityRows().size() > 0) {
                        Unit unit = getEngine().getOrganization().GetUnit(thisUnit.getEntityRows().get(0).getString("objectid"));
                        unit.setName(userData.getString("dept_content"));//名称
//                        unit.setSortKey(0);//排序值
                        if (userData.getString("dept_deleted").equals("1")) {
                            unit.setState(State.Inactive);
                        } else {
                            unit.setState(State.Active);
                        }
                        //Inactive(0),禁用 Active(1),启用 Unspecified(-1);
                        unit.setVisibility(VisibleType.Normal); //Normal(1),普通，同AllOnlyAdmin(2),管理员可见OnlyOrganization(4),仅本组织范围可见All(5);
                        unit.setParentIndex(0);
                        unit.setDescription(userData.getString("dept_id"));
                        unit.setExtend1(userData.getString("dept_code"));//组织iD
                        unit.setExtend2(userData.getString("dept_parentcode"));//所属组织 上级
                        getEngine().getOrganization().UpdateUnit(getAdministrator().getObjectID(), unit);
                    }
                }
            }
          //设计父组织
            for(DataRow userData : masonDepartmentList) {

                DataTable parentUnit = SqlUtil.doQuery(getH3UnSql+"'"+userData.getString("dept_parentcode")+"'");
                DataTable  thisUnit = SqlUtil.doQuery(getH3UnSql+"'"+userData.getString("dept_code")+"'");
                if(thisUnit!=null && thisUnit.getEntityRows().size()>0){
                    Unit unit = getEngine().getOrganization().GetUnit(thisUnit.getEntityRows().get(0).getString("objectid"));
                    if(parentUnit!=null && parentUnit.getEntityRows().size()>0 && !"".equals(userData.getString("dept_parentcode"))) {
                        unit.setParentID(parentUnit.getEntityRows().get(0).getString("objectid"));
                    }
                    if( "ROOT".equals(userData.getString("dept_parentcode"))) {
                        unit.setParentID(getEngine().getOrganization().getRootUnit().getObjectID());
                    }

                    getEngine().getOrganization().UpdateUnit(getAdministrator().getObjectID(), unit);
                }

            }
            try {
                getEngine().getOrganization().Reload();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            result="500";
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public String syncUserService() {
        try {
            getEngine().getOrganization().Reload();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String result = "200";
        SimpleDateFormat fm= new SimpleDateFormat("yyyy-mm-dd");
        List<DataRow>  userList = userDao.getUserList();
        try {
        for(DataRow map : userList){
            User h3User = null;
            h3User = getEngine().getOrganization().GetUserByCode(map.getString("emp_number"));
            String getH3UnSql= " select objectid,description from ot_organizationunit  where Description = ";
            if(h3User!=null) {
                String deptno ="";
                if(map.getString("dept_id")==null || "".equals(map.getString("dept_id").toString())){
                    deptno=getEngine().getOrganization().getRootUnit().getObjectID();
                }else{
                    deptno = map.getString("dept_id");
                }
                DataTable unitTable = SqlUtil.doQuery(getH3UnSql+"'"+deptno+"'");
                if( unitTable.getEntityRows().size()>0){
                    h3User.setParentID(unitTable.getEntityRows().get(0).getString("objectid"));
                }
                //Inactive(0),禁用 Active(1),启用Unspecified(-1);
//                h3User.setState(State.Active);
                //h3User.setEmployeeNumber(map.get("employeeno").toString()); 编号
                if(map.getString("emp_sex")!=null && "0".equals(map.getString("emp_sex").toString())) {
                    h3User.setGender(UserGender.Male);
                }else{
                    h3User.setGender(UserGender.Female);
                }
                if(map.getString("emp_entrydate")!=null && !"".equals(map.getString("emp_entrydate").toString())){
                    h3User.setEntryDate(fm.parse((map.getString("emp_entrydate"))));
                }
                if(map.getString("emp_quitdate")!=null && !"".equals(map.getString("emp_quitdate").toString())) {
                    h3User.setDepartureDate(fm.parse(map.getString("emp_quitdate").toString()));
                }
                h3User.setCode(map.getString("emp_number").toString());
                h3User.setName(map.getString("emp_name").toString());
                if(map.getString("emp_mobilephone")!=null) {
                    h3User.setMobile(map.getString("emp_mobilephone").toString());
                }
                h3User.setExtend1(map.getString("emp_id"));
                /*if(map.getString("dept_id")!=null && !"".equals(map.getString("dept_id"))) {
                    DataTable data = SqlUtil.doQuery(getH3UnSql+"'"+map.getString("dept_id").toString()+"'");

                    h3User.setParentID(data.getEntityRows().get(0).getString("objectid"));

                }*/
                getEngine().getOrganization().UpdateUnit(getAdministrator().getObjectID(),h3User );

            }else{
                //如果人员不存在则新增此人员
                h3User=new User();
                String deptno ="";
                if(map.getString("dept_id")==null || "".equals(map.getString("dept_id"))){
                    deptno=getEngine().getOrganization().getRootUnit().getObjectID();
                }else{
                    deptno = map.getString("dept_id");
                }
                DataTable unitTable = SqlUtil.doQuery(getH3UnSql+"'"+deptno+"'");
                if( unitTable.getEntityRows().size()>0){
                    h3User.setParentID(unitTable.getEntityRows().get(0).getString("objectid"));
                }
                h3User.setState(State.Inactive);
                //h3User.setEmployeeNumber(map.get("employeeno").toString()); 编号
                if(map.getString("emp_sex")!=null && "0".equals(map.getString("emp_sex").toString())) {
                    h3User.setGender(UserGender.Male);
                }else{
                    h3User.setGender(UserGender.Female);
                }
                if(map.getString("emp_entrydate")!=null && !"".equals(map.getString("emp_entrydate").toString())){
                    h3User.setEntryDate(fm.parse((map.getString("emp_entrydate"))));
                }
                if(map.getString("emp_quitdate")!=null && !"".equals(map.getString("emp_quitdate").toString())) {
                    h3User.setDepartureDate(fm.parse(map.getString("emp_quitdate").toString()));
                }
                h3User.setCode(map.getString("emp_number").toString());
                h3User.setName(map.getString("emp_name").toString());
                if(map.getString("emp_mobilephone")!=null) {
                    h3User.setMobile(map.getString("emp_mobilephone").toString());
                }
                h3User.setExtend1(map.getString("emp_id"));
               /*if(map.getString("dept_id")!=null && !"".equals(map.getString("dept_id"))) {
                   DataTable data = SqlUtil.doQuery(getH3UnSql+"'"+map.getString("dept_id").toString()+"'");
                   h3User.setParentID(data.getEntityRows().get(0).getString("objectid"));
                }*/
                getEngine().getOrganization().AddUnit(getAdministrator().getObjectID(),h3User);
            }

        }
            try {
                getEngine().getOrganization().Reload();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            result="500";
            e.printStackTrace();

        }
        return result;
    }
    @Override
    public String syncUserManager() {
        String result = "200";
        try {
            List<DataRow> masonDepartmentList = departmentDao.getDepartmentList();
            String getH3UnSql= " select objectid from ot_organizationunit  where state=1 and extend1 = ";
            String getUserId = "select objectid,code from ot_user where state=1 and extend1=";
       for(DataRow map : masonDepartmentList) {

             if(map.getString("dept_leaderid")!=null && !"".equals(map.getString("dept_leaderid").toString())) {
                 DataTable dataUnit =  SqlUtil.doQuery(getH3UnSql+"'"+map.getString("dept_id").toString()+"'");
                 DataTable data = SqlUtil.doQuery(getUserId+"'"+map.getString("dept_leaderid").toString()+"'");
                 if(dataUnit!=null && dataUnit.getEntityRows()!=null && dataUnit.getEntityRows().size()>0) {
                    Unit unit = getEngine().getOrganization().GetUnit( dataUnit.getEntityRows().get(0).getString("objectid"));
                     if (data != null && data.getEntityRows() != null && data.getEntityRows().size() > 0) {
                         unit.setParentID(data.getEntityRows().get(0).getString("objectid"));
                         getEngine().getOrganization().UpdateUnit(getAdministrator().getObjectID(),unit);
                     }

                 }

             }
        }


        } catch (Exception e) {
            result="500";
            e.printStackTrace();
        }
        return result;
    }

}
